﻿/**
 *
 * door.c
 *
 *  Created on: 2019-12-03
 *      Author: chenshisheng
 */

#include "door.h"
#include "hw.h"
#include "message_queue.h"
#include "power_manager.h"

static void _Exti(int data);

void Door_Init(void)
{
    HW_Config(HW_Out_Lock1, HW_State_Inactive);

    HW_SetExtiCallback(HW_Exti_LockIn1, _Exti, 0);
    HW_SetExtiCallback(HW_Exti_LockIn2, _Exti, 1);
}

bool Door_IsOpened(void)
{
    return HW_IsActive(HW_In_LockIn1) && HW_IsActive(HW_In_LockIn2);
}

bool Door_IsClosed(void)
{
    return (! HW_IsActive(HW_In_LockIn1)) && (! HW_IsActive(HW_In_LockIn2));
}

static void _Exti(int data)
{
    bool isOpened;

    if(Door_IsOpened())
    {
        isOpened = true;
        PowerManager_ExitLowPowerMode();
        MsgQueue_Send(MsgQueue_Id_DoorAction, & isOpened, sizeof(isOpened));
    }
    else if(Door_IsClosed())
    {
        isOpened = false;
        PowerManager_ExitLowPowerMode();
        MsgQueue_Send(MsgQueue_Id_DoorAction, & isOpened, sizeof(isOpened));
    }
}

int Door_Open(void)
{
    int i;

    HW_Config(HW_Out_Lock1, HW_State_Active);
    HAL_Delay(300);
    for(i = 0; i < (500 / 50); i++)
    {
        if(Door_IsOpened())
        {
            break;
        }

        HAL_Delay(50);
    }

    HW_Config(HW_Out_Lock1, HW_State_Inactive);
    return Door_IsOpened();
}

int Door_OpenCmd(Stream_t *stream, int argc, char *argv[])
{
    int lock, s;

    if(argc < 2)
    {
        chprintf(stream, "Lock1: %s\n", Door_IsOpened() ? "opened" : "closed");
    }
    else
    {
        lock = atoi(argv[1]);
        if(lock == 1)
        {
            chprintf(stream, "Opening lock1...\n");
            s = Door_Open();
            chprintf(stream, "Lock1: %s\n", s ? "opened" : "closed");
        }
        else
        {
            chprintf(stream, "Input Error!\n");
        }
    }

    return 0;
}
